<!DOCTYPE html>
<html>
<head>
  <title>Peg-Solitaire</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  <link href="css/site.css" rel="stylesheet">
  <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
  <![endif]-->

</head>
<body>
    <div class="container">
      <div class="col-md-3 col-xs-12">
        <ul class="nav nav-pills nav-stacked">
          <li class="active"><a href="#">Play</a></li>
          <li><a id="undo_link"> Undo </a></li>
          <li><a id="redo_link"> Redo </a></li>
          <li><a href="setup.jsp"> Setup </a></li>
        </ul>
        <div class="list-group">
          <a href="#" class="list-group-item">
            <h4 class="list-group-item-heading">Information</h4>
            <p class="list-group-item-text">Movements: <span class="label label-primary" id="movements"></span></p>
            <p class="list-group-item-text">Pins left: <span class="label label-warning" id="pinsLeft"></span></p>
            <% if(request.getParameter("timer") != null){ %>
            <p class="list-group-item-text">Time: <span class="label label-info" id="time">00:00</span></p>
            <% } %>
          </a>
        </div>
      </div>
      <div class="col-md-9 col-xs-12">
        <h1>Hi Q!</h1>
        <div class="tablero"></div>
        <div></div>
      </div>
    </div>
    <audio id="sonido" autoplay>
      <source id="mp3" src="" type="audio/mpeg">
      <embed id="emb" src="">
    </audio>
    <script src="js/holder.js"></script>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <script type="text/javascript" >
    var firstClick = true;
    var seconds = 0;
    var secondsInterval;
    var pegQuantity = 0;
    var movements = 0;
    var isFirst = true;
    //Rows and Columns
    var r0, c0;
    var r1, c1;

    var matrix;
    
    function showInMinutes(seg){
  	  var mod = seg % 60;
  	  var min = (seg - mod) / 60;
  	  return (min<10?"0":"") + min + ":" + (mod<10?"0":"") + mod;
    }
    
    function playSound(file){
      $("#mp3").attr("src","sound/"+file);
      $("#emb").attr("src","sound/"+file);
      $("#sonido").get(0).play();
    }
    
    function updateBadges(){
      $("#pinsLeft").html(pegQuantity);
      $("#movements").html(movements);
    }

    function sendData(r0,c0,r1,c1) {
      //console.log("Se envian los datos: ");
      //console.log("Primera-> " + r0 + "," + c0);
      //console.log("Segunda-> " + r1 + "," + c1);
      $.ajax( {
        url: "PlayFieldServlet",
        type: "POST",
        dataType: "JSON",
        data:{ r0 : r0, c0 : c0, r1 : r1, c1 : c1},
        success : function(data) {
          printMatrix(data);
          jugar();
        }
      });
    }

    function printMatrix(matrix) {
      pegQuantity = 0;
      var playField = $(".tablero");
      playField.html("");

      var content = "";

      for(var i = 0; i < 9; i++){
        for (var j = 0; j < 9; j++){

          var tipo = matrix[j][i];

          content += '<div id="f' + i + '' + j + '" class="peg ';
          if (tipo == 0) {
            //  content +="hole";
          } else if (tipo == 2) {
            content +="hole";
          } else {
            content +="pin";
            pegQuantity++;
          }
          content += '">&nbsp;</div>';
        }
        content +='<div class="clearfix"></div>';
      }
      playField.html(content);
      Holder.run();
      updateBadges();
    }

    function jump(id, type, ori){
      if(type == "h"){
        $("#f"+id).animate({
          left: (ori == "+"?"+":"-")+"=80"
        }, 1000, function(){}); 
      }
      else{
        $("#f"+id).animate({
          top: (ori == "+"?"+":"-")+"=80"
        }, 1000, function(){});
      }

    }

    function verticalJump(id, ori){
      jump(id, 'v', ori);
    }

    function horizontalJump(id, ori){
      jump(id,'h',ori);
    }
    function jugar(){
      $(".tablero div").click(function(){
        var id = $(this).attr('id');
        r = id[1];
        c = id[2];
        if(isFirst) {
          isFirst = false;
          r0 = id[1];
          c0 = id[2];
          r1 = null;
          c1 = null;
        }
        else {
          isFirst = true; 
          r1 = id[1];
          c1 = id[2];
          if(r0 < r1 && c0 == c1)
            verticalJump(""+r0+c0,'+');
          if(r0 > r1 && c0 == c1)
            verticalJump(""+r0+c0,'-');
          if(c0 < c1 && r0 == r1)
            horizontalJump(""+r0+c0,'+');
          if(c0 > c1 && r0 == r1)
            horizontalJump(""+r0+c0,'-');
          setTimeout(function(){
            sendData(r0,c0,r1,c1);
            movements++;
            updateBadges();
            playSound("plop.mp3");
            if(pegQuantity == 2){
           	  clearInterval(secondsInterval);
           	  <% if(request.getParameter("timer") != null){ %>
           	  alert("Has Ganado en " + showInMinutes(seconds) + " minutos, felicitaciones!!");
           	  <% }else{ %>
           	  alert("Has Ganado, felicitaciones!!");           		  
           	  <% } %>
           	  window.location = "setup.jsp";
            }
          },1000);
        }  
      });
    }

    $(document).ready(function() {

      $("#undo_link").click( function(){
        if(movements != 0){
          $.ajax( {
            url: "PlayFieldServlet",
            type: "POST",
            dataType: "JSON",
            data:{ undo: true},
            success : function(data) {
              printMatrix(data);
              jugar();
              movements--;
              updateBadges();
            }
          });  
        }
        else{
          alert("There are not enough undo actions");
        }
      } );
      
      $("#redo_link").click( function(){
        $.ajax( {
          url: "PlayFieldServlet",
          type: "POST",
          dataType: "JSON",
          data:{redo: true},
          success : function(data) {
            printMatrix(data);
            jugar();
            movements++;
            updateBadges();
          }
        });  
      } );
      
      <% if(request.getParameter("timer") != null){ %>
      $(".tablero").click(function() {
      	if(firstClick){
	        	secondsInterval = setInterval(function () {
	    		  ++seconds;
	    		  $("#time").html(showInMinutes(seconds));
	       		}, 1000);
	        	firstClick = !firstClick;
      	}
		});
      <% } %>
      $.ajax( {
        url: "PlayFieldServlet",
        type: "GET",
        <%
        if(request.getParameter("config") != null){
          out.println("data: {config : '"+request.getParameter("config")+"'},");
        }
        %>
        dataType: "JSON",
        success : function(data) {
          matrix = data;
          printMatrix(matrix);
          jugar();
        }
      });
    });
    </script>
  </body>
</html>